import { useCallback, useMemo } from 'react';
import { getFormItems } from './form';
import { formatRenderData, formatSubmitData } from './format';
import type { ConfigProps } from './type.d.ts';

export enum FORM_TYPE {
  SEARCH = 'SEARCH',
  EDIT = 'EDIT',
}

const useTableAndFormConfig = (configList: ConfigProps[]) => {
  const {
    tableColumns,
    searchConfig,
    editConfig,
    searchFormItems,
    editFormItems,
  } = useMemo(() => {
    const reduceConfigs = (acc: any, item: ConfigProps) => {
      if (!item) return acc;
      const { hideInEdit, hideInSearch, hideInTable } = item;
      if (!hideInTable) acc.tableColumns.push(item);
      if (!hideInSearch) acc.searchConfig.push(item);
      if (!hideInEdit) acc.editConfig.push(item);
      return acc;
    };
    const initialAcc = {
      tableColumns: [],
      searchConfig: [],
      editConfig: [],
    };
    const reduced = configList.reduce(reduceConfigs, initialAcc);
    return {
      ...reduced,
      searchFormItems: getFormItems(reduced.searchConfig, FORM_TYPE.SEARCH),
      editFormItems: getFormItems(reduced.editConfig, FORM_TYPE.EDIT),
    };
  }, [configList]);

  const formatData = useCallback(
    (formType: FORM_TYPE, data: Record<string, any>, isSubmit: boolean) => {
      const config = formType === FORM_TYPE.EDIT ? editConfig : searchConfig;
      return isSubmit
        ? formatSubmitData(config, data)
        : formatRenderData(config, data);
    },
    [editConfig, searchConfig],
  );

  return {
    tableColumns,
    searchFormItems,
    editFormItems,
    formatSubmit: (formType: FORM_TYPE, values: Record<string, any>) =>
      formatData(formType, values, true),
    formatRender: (formType: FORM_TYPE, data: Record<string, any>) =>
      formatData(formType, data, false),
    FORM_TYPE,
  };
};

export default useTableAndFormConfig;
